package com.loyal.mwm.ext

import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.text.HtmlCompat
import com.base.R

fun View.delayClick() {
    isClickable = false
    postDelayed({ isClickable = true }, 800L)
}

fun View.delayEnable() {
    isEnabled = false
    postDelayed({ isEnabled = true }, 800L)
}

fun View.backgroundResource(empty: Boolean, @ColorRes rightColor: Int = R.color.bodyColor) {
    val color = if (empty) R.color.transparent else rightColor
    setBackgroundResource(color)
}

fun Spinner.onItemSelected(itemSelected: (obj: Any?) -> Unit) {
    onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val objBean = parent?.adapter?.getItem(position)
            itemSelected.invoke(objBean)
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }
}

fun TextView.fromHtml(source: String) {
    text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

fun TextView.startFromHtml(start: String?, end: String?, color: String = "#99B9FF") {
    /*if (!color.startsWith("#")) {
            color = "#" + color;
        }*/
    val source = String.format("<font color='%s'>%s</font>%s", color, start, end)
    fromHtml(source)
}

fun TextView.endFromHtml(start: String?, end: String?, color: String = "#99B9FF") {
    /*if (!color.startsWith("#")) {
            color = "#" + color;
        }*/
    val source = String.format("%s<font color='%s'>%s</font>", start, color, end)
    fromHtml(source)
}

fun TextView.stateChange(sequence: CharSequence? = null) {
    text = sequence
    visibility = if (TextUtils.isEmpty(text)) View.GONE else View.VISIBLE
}